package top.viya.hello2.redis.common;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class RedisUtils {
    @Resource(name = "stringRedisTemplate")
    private RedisTemplate<String, String> stringRedisTemplate;

    private DefaultRedisScript<Long> memoryUsageScript;

    @PostConstruct
    void init() {
        memoryUsageScript = buildMemoryUsageScript();
    }

    public Long getKeyMemorySize(String key) {
        return stringRedisTemplate.execute(memoryUsageScript, Collections.singletonList(key));
    }

    private DefaultRedisScript<Long> buildMemoryUsageScript() {
        DefaultRedisScript<Long> memoryUsageScript = new DefaultRedisScript<>();
        memoryUsageScript.setScriptText("return redis.call('memory', 'usage', KEYS[1])");
        memoryUsageScript.setResultType(Long.class);
        return memoryUsageScript;
    }
}
